package com.yiwei.hdb.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.hdb.R;
import com.yiwei.hdb.api.callback.WithdrawApplyContract;
import com.yiwei.hdb.api.requestInfo.WithdrawApplyRequest;
import com.yiwei.hdb.constant.Const;
import com.yiwei.hdb.constant.UserGlobal;
import com.yiwei.hdb.event.OnCloseMyfund;
import com.yiwei.hdb.event.OnHomeEventMsg;
import com.yiwei.hdb.event.SelectBankWithdrawEvent;
import com.yiwei.hdb.model.ApplyModel;
import com.yiwei.hdb.model.BankCardListModel;
import com.yiwei.hdb.model.BankListModel;
import com.yiwei.hdb.model.MoneyLogModel;
import com.yiwei.hdb.model.MyFundInfoModel;
import com.yiwei.hdb.model.SupportBankModel;
import com.yiwei.hdb.model.UserModel;
import com.yiwei.hdb.util.PreferenceUtils;
import com.yiwei.hdb.util.Spans;
import com.yiwei.hdb.util.ToastUtil;
import com.yiwei.hdb.util.UI;
import com.yiwei.hdb.util.Util;
import com.yiwei.hdb.view.BankViewItem;
import com.yiwei.hdb.view.CircularProgress;
import com.yiwei.hdb.view.Dialog;
import com.yiwei.hdb.view.LastInputEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.yiwei.hdb.R.id.money;

/**
 * Created by xsooy-pc on 2017/9/20.
 */

public class WithdrawV2Activity extends BaseActivity implements WithdrawApplyContract.View {

    @BindView(R.id.img_icon)
    ImageView imgIcon;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.bank_view)
    RelativeLayout bankView;
    @BindView(R.id.txt_money_all)
    TextView txtMoneyAll;
    @BindView(R.id.btn_all)
    SuperButton btnAll;
    @BindView(R.id.edit_money)
    LastInputEditText editMoney;
    @BindView(R.id.txt_shouxu_fee)
    TextView txtShouxuFee;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.progressBar)
    CircularProgress loading;
    //    @BindView(R.id.layout_unbind)
//    LinearLayout layoutUnbind;
    private WithdrawApplyRequest api;
    private String realName;
    private BankViewItem bankViewItem;
    private int px26;
    //    private String shouxufee;
    private float money;
    private Unbinder unbiner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.activity_withdraw_v2);
        unbiner = ButterKnife.bind(this);
        baseInitView(this, "WithdrawV2Activity", Const.ViewType.ACTIVITY);
        initView();
        EventBus.getDefault().register(this);

    }

    private void showLoading(boolean b) {
        if (loading != null) {
            if (b)
                loading.setVisibility(View.VISIBLE);
            else
                loading.setVisibility(View.GONE);
        }
    }

    private boolean isEmpty = true;

    private void initView() {
        editMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(UI.toString(editMoney))) {
                    isEmpty = true;
                    btnSubmit.setBackgroundResource(R.drawable.update_btn_grey_bg);
                } else {
                    if (isEmpty) {
                        isEmpty = false;
                        btnSubmit.setBackgroundResource(R.drawable.home_btn_bg);
                    }
                }
            }
        });

        px26 = getResources().getDimensionPixelSize(R.dimen.x26);
        setTitleText(getResources().getString(R.string.withdraw));
        setBackIntent();
        api = WithdrawApplyRequest.create();
        api.attachView(this);
        api.getDealDetailInfo();
        api.getBankList();
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
        showLoading(false);
    }

    @Override
    public void onRequestStart() {
        showLoading(true);
    }

    private boolean isBind = false;

    @Override
    public void getBankListSuccess(BankCardListModel model) {
        if (model.data.size() <= 0) {
            isBind = false;
            bankView.setVisibility(View.GONE);
            return;
        }
        isBind = true;
        bankView.setVisibility(View.VISIBLE);
//        realName = model.getReal_name();
        name.setText(model.data.get(0).bank.name);
        String bankCard = model.data.get(0).bankcard;
        String cardType = getResources().getString(R.string.card_text2);
//        if (!TextUtils.isEmpty(model.getBanks().get(0).getCardtype()))
//            cardType = model.getBanks().get(0).getCardtype();
        if (bankCard.contains("*")) {
            text.setText(bankCard);
        } else {
            text.setText(Util.hideCardNo(bankCard));
        }


        bankViewItem = new BankViewItem();
        int id = bankViewItem.getBankRes(model.data.get(0).bank.name);
        imgIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), bankViewItem.bankImg[id]));
    }

    @Override
    public void getDealDetailInfoSuccess(MyFundInfoModel item) {
//        money = Float.valueOf(item.user_balance);
//        String shouxufei = item.user.cash_server_fee;
//        Spanned ketixian = Spans.with(this).font("可提现金额", px26, 0xffcacaca).
//                font(money + "", px26, 0xfff8554a).
//                font("元", px26, 0xffcacaca).
//                build();

        txtMoneyAll.setText(item.data.money + "");
        if (!TextUtils.isEmpty(item.data.money)) {
            money = Float.valueOf(item.data.money);
        }
//        Spanned shouxu = Spans.with(this).font("手续费", px26, 0xffD8DBE9).
//                font(shouxufei + "", px26, 0xffFE5A59).
//                font("元", px26, 0xffD8DBE9).
//                build();
//        txtShouxuFee.setText(shouxu);
    }

    @Override
    public void getWithdrawApplySuccess(ApplyModel item) {
        if (item.getStatus() == 1) {
//            Util.startActivity(this, DebtDetailActivity.class);
//            finish();
            Dialog.showWithdrawSuccessDialog(this, new Dialog.DialogClickListener() {
                @Override
                public void confirm() {
                    finish();
                }
            });
        } else if (item.getStatus() == 2) {
            Dialog.gotoRepayMoney(this, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    EventBus.getDefault().post(new OnCloseMyfund());
                    sendEventBus();
                    finish();
                }

                @Override
                public void cancel() {

                }
            }).show();
        } else {
            ToastUtil.makeText(this, item.getMsg()).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void sendEventBus() {

        Map<String, String> map = new HashMap<>();
        map.put("type", Const.SendType.SWITCH_PAGE);
        map.put("currentIndex", Const.View.REPAY_VIEW + "");
        EventBus.getDefault().post(new OnHomeEventMsg(map));
        Util.startActivity(this, MainActivityNew.class);
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectMoney(SelectBankWithdrawEvent msg) {

        isBind = true;
        bankView.setVisibility(View.VISIBLE);
//        realName = model.getReal_name();
        name.setText(msg.item.bank.name);
        String bankCard = msg.item.bankcard;
        String cardType = getResources().getString(R.string.card_text2);
//        if (!TextUtils.isEmpty(model.getBanks().get(0).getCardtype()))
//            cardType = model.getBanks().get(0).getCardtype();
        if (bankCard.contains("*")) {
            text.setText(bankCard);
        } else {
            text.setText(Util.hideCardNo(bankCard));
        }


        bankViewItem = new BankViewItem();
        int id = bankViewItem.getBankRes(msg.item.bank.name);
        imgIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), bankViewItem.bankImg[id]));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
    }

    @OnClick({R.id.btn_all, R.id.btn_submit, R.id.bank_view})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_all:
                editMoney.setText((int) money + "");
                break;
            case R.id.bank_view:
                if (!UserGlobal.getIsIdcardPass()) {
                    ToastUtil.makeText(this, "请先完成实名");
                    Util.startActivity(this, V3IdcardIdentityActivity.class);
                    return;
                }

//                Util.startActivity(this, V3BankMoreListActivity.class);
                Intent intent=new Intent(this,V3BankMoreListActivity.class);
                intent.putExtra("is_click",true);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
//            case R.id.layout_unbind:
//                Util.startActivity(this, V3BankEditActivity.class);
//                break;
            case R.id.btn_submit:
                if (!isBind) {
                    ToastUtil.makeText(this, "请绑定银行卡").show();
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editMoney))) {
                    ToastUtil.makeText(this, "提现金额不能为空").show();
                    return;
                }
                if (UI.toFloat(editMoney) < 50) {
                    ToastUtil.makeText(this, "提现金额必须大于50").show();
                    return;
                }
                api.getWithdrawApply(UI.toString(editMoney));
                break;
        }
    }
}
